//
//  ITShareManager.m
//  ITBE
//
//  Created by figs on 2019/8/6.
//  Copyright © 2019年 鲍利成. All rights reserved.
//

#import "ITShareManager.h"
#import "ITAppStartManager.h"
#import "ITDeviceInfo.h"
@implementation ITShareModel

@end

@implementation ITShareManager

+ (instancetype)shareManager{
    static ITShareManager *_manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [ITShareManager new];
    });
    return _manager;
}

+ (BOOL)isFBInstall{
    return [self isInstallWithPlatforType:ITPlatformTypeFB];
}

+ (BOOL)isInstallWithPlatforType:(ITPlatformType)platformType{
    NSString *scheme = nil;
    switch (platformType) {
        case ITPlatformTypeFB:
            scheme = @"fbauth";
            break;
        case ITPlatformTypeFBMessenger:
            scheme = @"fb-messenger";
            break;
        case ITPlatformTypeTwiter:
            scheme = @"twitter";
            break;
        case ITPlatformTypeWhatsapp:
            scheme = @"whatsapp";
            break;
        default:
            break;
    }
    if (scheme == nil) {
        return NO;
    }
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@://", scheme]];
    return [[UIApplication sharedApplication] canOpenURL:url];
}

+ (NSMutableArray *)supportItems{
    //type（分享方式）：1.facebook，2.instagram，3.whatsAPP，4.messenger，5.copy link
    //NSArray *activePlatforms = [ShareSDK activePlatforms];
    NSMutableArray *items = [NSMutableArray array];
    if ([AppUtils DICT_WORK_MODE]) {
        ITShareModel *model = [ITShareModel new];
        
        if ([self isInstallWithPlatforType:ITPlatformTypeWhatsapp]) {
            model = [ITShareModel new];
            model.platformType = ITPlatformTypeWhatsapp;
            model.showTitle = @"WhatsApp";
            model.showImageName = @"ShareWhatsApp";
            model.shareType = @"whatsapp";
            model.iconName = @"\U0000e936";
            [items addObject:model];
        }
        
        model.platformType = ITPlatformTypeFB;
        model.showTitle = @"Facebook";
        model.shareType = @"facebook";
        model.showImageName = @"ShareFacebook";
        model.iconName = @"\U0000e600";
        [items addObject:model];
        
        if ([self isInstallWithPlatforType:ITPlatformTypeTwiter]){
            model = [ITShareModel new];
            model.platformType = ITPlatformTypeTwiter;
            model.showTitle = @"Twitter";
            model.showImageName = @"ShareTwitter";
            model.shareType = @"twitter";
            model.iconName = @"\U0000e60d";
            [items addObject:model];
        }
        
        /*
        if ([self isInstallWithPlatforType:SSDKPlatformTypeFacebookMessenger]) {
            model = [ITShareModel new];
            model.platformType = SSDKPlatformTypeFacebookMessenger;
            model.showTitle = @"Messenger";
            model.showImageName = @"ShareMessenger";
            model.shareType = @"messenger";
            [items addObject:model];
        }//*/
    }
    return items;
}

+ (ITShareModel *)copyModel{
    ITShareModel *copy = [ITShareModel new];
    copy.showTitle = [AppUtils titleForKey:@"Copylink"];
    copy.platformType = ITPlatformTypeCopy;
    copy.showImageName = @"ShareCopylink";
    copy.shareType = @"copylink";
    return copy;
}

- (void)install{
    /*
    [ShareSDK registPlatforms:^(SSDKRegister *platformsRegister) {
        //Facebook
        [platformsRegister setupFacebookWithAppkey:@"426233721389355" appSecret:@"2b5a6d5768cd760e218aaa4f4784d515" displayName:[ITDeviceInfo getBundleDisplayName]];
        
//        //Twitter
//        [platformsRegister setupTwitterWithKey:@"viOnkeLpHBKs6KXV7MPpeGyzE" secret:@"NJEglQUy2rqZ9Io9FcAU9p17omFqbORknUpRrCDOK46aAbIiey" redirectUrl:@"http://mob.com"];
    }];
     //*/
}


- (void)shareWebPageWithModel:(ITShareModel *)model callback:(ShareBlock)callback{
    
    [self shareWebPageToPlatformType:model.platformType title:model.title description:model.desc thumImage:model.thumImage webpageUrl:model.webPageUrl callback:callback];
}
/*
- (void)shareWebPageToPlatformType:(int)platformType title:(NSString *)title description:(NSString *)desc thumImage:(id)image webpageUrl:(NSString *)webpageUrl callback:(ShareBlock)callback{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    //Facebook Messenger分享链接，图片必须是网络图片链接
    if (platformType == SSDKPlatformTypeFacebook || platformType == SSDKPlatformTypeFacebookMessenger ){
        if (![image isKindOfClass:[NSString class]]) {
            image = nil;
        }
    }else {
        if ([image isKindOfClass:[NSString class]]) {
            image = [[YYImageCache sharedCache] getImageForKey:image];
        }
    }
    switch (platformType) {
        case SSDKPlatformTypeFacebook:{
            [params SSDKSetupFacebookParamsByText:desc image:image url:[NSURL URLWithString:webpageUrl] urlTitle:title urlName:desc attachementUrl:nil hashtag:nil quote:nil shareType:SSDKFacebookShareTypeNative type:SSDKContentTypeWebPage];
            }
            break;
        case SSDKPlatformTypeTwitter:{
            title = [desc stringByAppendingFormat:@" %@",webpageUrl];
            [params SSDKSetupTwitterParamsByText:title images:image video:nil latitude:0 longitude:0 type:SSDKContentTypeText];
        }
            break;
        case SSDKPlatformTypeWhatsApp:{
            title = [desc stringByAppendingFormat:@" %@",webpageUrl];
            [params SSDKSetupWhatsAppParamsByText:title image:image audio:nil video:nil menuDisplayPoint:CGPointZero type:SSDKContentTypeText];
        }
            break;
        case SSDKPlatformTypeFacebookMessenger:{
            //title = [title stringByAppendingFormat:@" %@",webpageUrl];
            //webpageUrl = @"https://www.facebook.com";
            [params SSDKSetupFacebookMessengerParamsByTitle:title url:[NSURL URLWithString:webpageUrl] quoteText:desc images:nil gif:nil audio:nil video:nil type:SSDKContentTypeWebPage];
            //[params SSDKSetupShareParamsByText:title images:nil url:[NSURL URLWithString:webpageUrl] title:desc type:SSDKContentTypeAuto];
        }
            break;
            
        default:
            break;
    }
    //[params SSDKSetupShareParamsByText:title images:image url:[NSURL URLWithString:webpageUrl] title:@"title" type:type];
    
    [ShareSDK share:platformType parameters:params onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
        if (callback) {
            callback(state == SSDKResponseStateSuccess);
        }
        if (state == SSDKResponseStateSuccess) {
            [AppUtils showInfo:[AppUtils titleForKey:@"Share successfully"]];
        }
        switch (state) {
            case SSDKResponseStateUpload:
                // 分享视频的时候上传回调，进度信息在 userData
                break;
            case SSDKResponseStateSuccess:
                if (platformType == SSDKPlatformTypeTwitter) {
                    
                }
                //成功
                break;
            case SSDKResponseStateFail:
            {
                NSLog(@"--%@",error.description);
                //失败
                break;
            }
            case SSDKResponseStateCancel:
                //取消
                break;
                
            default:
                break;
        }
    }];
}


- (void)authorizeWithPlatforType:(SSDKPlatformType)platformType authorizeBlock:(AuthorizeBlock)authorizeBlock{
    [ShareSDK authorize:platformType settings:@{@"isBrowser":@(NO)} onStateChanged:authorizeBlock];
}
- (void)getUserInfoWithPlatforType:(SSDKPlatformType)platformType authorizeBlock:(AuthorizeBlock)authorizeBlock{
    [ShareSDK getUserInfo:platformType onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
        if (authorizeBlock) {
            authorizeBlock(state, user, error);
        }
        if (state == SSDKResponseStateSuccess) {
            [ShareSDK cancelAuthorize:platformType result:nil];
        }
    }];
}
//*/

+ (void)trackEnentNo:(NSString *)enentNo params:(NSDictionary *)params{
    //[AppUtils trackMTAEventNo:enentNo pageNo:pateNo parameters:params];
    NSMutableDictionary *tmp = [NSMutableDictionary dictionaryWithDictionary:params?: [NSDictionary dictionary]];
    tmp[@"shareid"] = enentNo;
    //[AppUtils trackMTAEventNo:@"vq_10003" parameters:tmp];
}

/**分享url  videoid 为空 则是分享应用*/
+ (NSString *)shareUrlWithEventNo:(NSString *)eventNo shareType:(NSString *)shareType videoId:(NSString *)videoId{
    ITUserInfo *host = [ITUserManager currentMember];
    
    NSString *uname = host.name.stringByURLEncode;
    NSString *avatar = host.portrait.stringByURLEncode;
    
    NSString *p = [@"ios&" stringByAppendingFormat:@"%@&%@&%@&%@",shareType, eventNo.stringByURLEncode, uname, avatar];
    NSString *cb = [NSString stringWithFormat:@"code=%@&channel=%@",host.inviterCode?:@"", shareType];
    NSString *paramsString = [NSString stringWithFormat:@"p=%@&cb=%@",p.stringByURLEncode ,cb.stringByURLEncode];
    NSString *shareUrl = nil;
    if (videoId.length > 0) {
        shareUrl = [[AppUtils returnShareH5BaseUrl] stringByAppendingFormat:@"/shared/%@/share?%@", videoId, paramsString];
    }else {
        shareUrl = [[AppUtils returnShareH5BaseUrl] stringByAppendingFormat:@"/shared/invite?%@", paramsString];
    }
    return shareUrl;
}


+ (BOOL)shouldShowShareVideo{
    ITCommonConfig *share = [ITGeneralManager.defaultManager configDicWithKey:@"DICT_WEBSITE_SHARE"];
    if (share && share.value.length > 1) {
        return YES;
    }
    return NO;
}


/**
 分享url规则,添加mid字段
 ?vid={videoId}&inid={interactionId}&intype={type}&mid={memberId}
 interactionId 为空时, 不传inid 和 intype
 memberId为当前用户ID
 */
/*
- (void)shareVideo:(ITVideoModel *)video{
    NSString *title = video.title;
    long  videoId = video.rootId ?: video.videoId;
    NSString *uri = [NSString stringWithFormat:@"?vid=%ld&mid=%@", videoId, ITUserManager.currentMember.memberId];
    NSString *url = [[AppUtils returnShareH5BaseUrl] stringByAppendingString:uri];
    WEAKSELF
    MBProgressHUD *progress = [AppUtils showLoading];
    [BaseImageView imageWithUrl:video.cover callback:^(UIImage * _Nonnull image) {
        [weak_self shareWithTitle:title image:image url:url];
        [progress hideAnimated:YES];
    }];
}
//*/

- (void)shareWithTitle:(NSString *)title image:(UIImage *)image url:(NSString *)url{
    NSArray *activityItems = @[[NSURL URLWithString:url], title, image];
    UIActivityViewController* controller =  [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    [[AppUtils findRootController] presentViewController:controller animated:YES completion:nil];
    controller.excludedActivityTypes = [self excludetypes];
    [controller setCompletionWithItemsHandler:^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        NSLog(@"当前选择分享平台%@",activityType);
        if(completed) {
            NSLog(@"分享成功");
        }else{
            NSLog(@"分享失败");
        }
    }];
}


-(NSArray *)excludetypes{
    //com.tencent.xin.sharetimeline
    //com.zhihu.ios.Share
    //com.apple.UIKit.activity.PostToFacebook
    //com.apple.UIKit.activity.PostToTwitter
    //com.burbn.instagram.shareextension
    //com.facebook.Messenger.ShareExtension
    //com.nicegram.Telegram-iOS.Share
    //com.laiwang.DingTalk.ShareExtension
    //com.apple.reminders.sharingextension
  NSMutableArray *excludeTypesM =  [NSMutableArray arrayWithArray:@[
                                                                    //UIActivityTypePostToFacebook,
                                                                    //UIActivityTypePostToTwitter,
                                                                    //UIActivityTypePostToWeibo,
                                                                    //UIActivityTypeMessage,
                                                                    //UIActivityTypeMail,
                                                                    UIActivityTypePrint,
                                                                    //UIActivityTypeCopyToPasteboard,
                                                                    UIActivityTypeAssignToContact,
                                                                    UIActivityTypeSaveToCameraRoll,
                                                                    UIActivityTypeAddToReadingList,
                                                                    UIActivityTypePostToFlickr,
                                                                    UIActivityTypePostToVimeo,
                                                                    UIActivityTypePostToTencentWeibo,
                                                                    //UIActivityTypeAirDrop,
                                                                    UIActivityTypeOpenInIBooks]];
  
  if ([[UIDevice currentDevice].systemVersion floatValue] >= 11.0) {
      [excludeTypesM addObject:UIActivityTypeMarkupAsPDF];
  }
  
  return excludeTypesM;
}



@end
